package com.supermap.application.service;

import com.supermap.application.dao.BaseDaoImpl;
import com.supermap.application.entity.TBaseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 产业链业务层
 */
@Service
public class IndustryChainService {

    /** 实体管理 */
    @Autowired
    @PersistenceContext
    private EntityManager entityManager;


    /**
     * 执行原生SQL 语法的方法
     * @param sql
     * @return
     */

    public List<Object> queryBySql(String sql) {
        BaseDaoImpl<TBaseData,Integer> dao = new BaseDaoImpl<>(TBaseData.class,entityManager);
        List<Object> list = dao.query(sql);
        return list;
    }


    /**
     * 将取出来的数据转化成jason格式的通用方法
     * @param mapRet
     * @param data
     * @param rootKey
     * @param arrKeys
     */
    public void findIndustryAnalysis(LinkedHashMap mapRet, List<Object> data, String rootKey , List<String> arrKeys){
        int nFieldsCount = arrKeys.size();
        boolean bSingleField = arrKeys.size()==1;
        int nRecordCount = data.size();

        LinkedHashMap[] QueryResult = null;
        QueryResult = new LinkedHashMap[nRecordCount];
        for(int i=0;i<nRecordCount;i++){
            if(!bSingleField) {   //多列
                Object[] obj =(Object[]) data.get(i);
                if(obj != null &&obj.length>=nFieldsCount){
                    QueryResult[i] = new LinkedHashMap();
                    for(int j=0;j<nFieldsCount;j++) {
                        QueryResult[i].put(arrKeys.get(j), obj[j]);
                    }

                }
            }else {  //单列
                Object objProject = data.get(i);
                if (objProject != null) { // objProject.length 与 SQL查询的字段数 一样
                    QueryResult[i] = new LinkedHashMap();
                    QueryResult[i].put(arrKeys.get(i), objProject );
                    //                   System.out.println("---------");
                }
            }
        }
        if( QueryResult != null ) {
            mapRet.put(rootKey, QueryResult);
        }
        else {
            mapRet.put(rootKey, "");
        }
    }
}
